package com.niodata.dp.monitor.common.service;

import com.google.common.base.Strings;
import com.niodata.dp.monitor.common.configure.MonitorConfigurationKeys;
import com.niodata.dp.monitor.common.util.ConfigUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Created by ndp on 17-4-20.
 */
public class RedisPool {

  private static RedisPool pool;

  static {
    pool = new RedisPool();
  }

  private String addr;
  private int port = 6379;
  private JedisPool jedisPool;

  /**
   * RedisPool.
   */
  private RedisPool() {
    try {
      JedisPoolConfig config = new JedisPoolConfig();
      config.setMaxTotal(100);
      config.setMaxIdle(10);
      config.setMinIdle(5);
      config.setMaxWaitMillis(5000);
      addr = ConfigUtil.getInstance().getString(MonitorConfigurationKeys.REDIS_IP);
      String portStr = ConfigUtil.getInstance().getString(MonitorConfigurationKeys.REDIS_PORT);
      if (!Strings.isNullOrEmpty(portStr)) {
        port = Integer.parseInt(portStr);
      }
      if (Strings.isNullOrEmpty(addr)) {
        throw new RuntimeException("redis.ip not configed");
      }
      String password = ConfigUtil.getInstance().getString("redis.password", null);
      if (password != null) {
        jedisPool = new JedisPool(config, addr, port, 60, password);
      } else {
        jedisPool = new JedisPool(config, addr, port, 60);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public static RedisPool getInstance() {
    return pool;
  }

  public JedisPool getJedisPool() {
    return jedisPool;
  }

  public Jedis getConnection() {
    return jedisPool.getResource();
  }

}
